import React, { useState, useEffect, useCallback, useReducer } from 'react';
import { Button, Layout, Typography, Modal, Progress, Spin, Divider, Tag, Alert } from 'antd';
import { useNavigate, useLocation } from 'react-router-dom';
import { motion, AnimatePresence } from 'framer-motion';
import './GamePage.css'; // 导入CSS文件
import AnimatedText from '../components/AnimatedText';
import LegalParticlesBackground from '../components/LegalParticlesBackground';
import LegalDecorations from '../components/LegalDecorations';
import LegalCard from '../components/LegalCard';
import AnimatedButton from '../components/AnimatedButton';
import AnimatedDice from '../components/AnimatedDice';
import LegalConceptPuzzle from '../components/LegalConceptPuzzle';
import legalConcepts from '../data/legalConcepts';

const { Header, Content, Footer } = Layout;
const { Title, Text, Paragraph } = Typography;

// 玩家状态reducer
const playerReducer = (state, action) => {
  switch (action.type) {
    case 'INIT':
      return action.payload;
    case 'LOSE_HEALTH':
      return { ...state, health: Math.max(0, state.health - 1) };
    case 'ADD_HEALTH':
      return { ...state, health: state.health + action.payload };
    case 'ADD_ATTACK':
      return { ...state, attack: state.attack + action.payload };
    case 'MULTIPLY_HEALTH':
      return { ...state, health: state.health * action.payload };
    case 'MULTIPLY_ATTACK':
      return { ...state, attack: state.attack * action.payload };
    case 'ADD_DICE':
      return { ...state, dice: state.dice + action.payload };
    case 'USE_DICE':
      return { ...state, dice: Math.max(0, state.dice - 1) };
    default:
      return state;
  }
};

// 添加防抖工具函数
const debounce = (func, wait) => {
  let timeout;
  return function executedFunction(...args) {
    const later = () => {
      clearTimeout(timeout);
      func(...args);
    };
    clearTimeout(timeout);
    timeout = setTimeout(later, wait);
  };
};

const GamePage = ({ onGameEnd }) => {
  const navigate = useNavigate();
  const location = useLocation();
  const gameParams = React.useMemo(() => {
    console.log('location.state:', location.state);
    return location.state || {};
  }, [location.state]);
  
  // 添加标志防止重复初始化和请求
  const isInitialLoadRef = React.useRef(true);
  const isLoadingRef = React.useRef(false);
  const requestInProgressRef = React.useRef(false);
  
  console.log('GamePage接收到的参数:', gameParams);
  console.log('location对象:', location);

  // 关卡Boss配置
  const bossConfig = React.useMemo(() => [
    // 第一关
    { 
        level: 1, 
        health: 10, 
        attack: 1, 
        effect: {
            name: "无",
            description: "普通关卡，无特殊效果"
        } 
    },
    // 第二关
    { 
        level: 2, 
        health: 20, 
        attack: 1, 
        effect: {
            name: "恶意程序劫持",
            description: "每回合有30%概率使玩家无法使用技能"
        } 
    },
    // 第三关
    { 
        level: 3, 
        health: 30, 
        attack: 2, 
        effect: {
            name: "法域迷雾",
            description: "隐藏题目中的关键法律条款"
        } 
    },
    // 第四关
    { 
        level: 4, 
        health: 40, 
        attack: 3, 
        effect: {
            name: "权利滥用",
            description: "Boss攻击时有50%概率造成双倍伤害" 
        } 
    },
    // 第五关
    { 
        level: 5, 
        health: 50, 
        attack: 5, 
        effect: {
            name: "终局威慑",
            description: "Boss免疫所有技能效果，且每回合攻击力增加1点"
        } 
    }
  ], []);
  
  // 初始化玩家状态
  const initPlayerState = () => {
    const style = gameParams.style?.value;
    console.log('选择的风格:', style);
    
    let health = 4; // 默认值
    let attack = 2; // 默认值
    
    if (style === 'conservative') {
      health = 6;
      attack = 1;
    } else if (style === 'balanced') {
      health = 4;
      attack = 2;
    } else if (style === 'aggressive') {
      health = 2;
      attack = 3;
    }
    
    return {
      health,
      attack,
      dice: gameParams.dice || 0,
      style: style
    };
  };
  
  // 使用useReducer管理玩家状态
  const [player, dispatchPlayer] = useReducer(playerReducer, null, initPlayerState);
  
  // 游戏状态
  const [currentLevel, setCurrentLevel] = useState(1); // 当前关卡
  const [bossHealth, setBossHealth] = useState(bossConfig[0].health);
  const [bossAttack, setBossAttack] = useState(bossConfig[0].attack); // 侵权烈度
  const [bossSpecialEffect, setBossSpecialEffect] = useState(bossConfig[0].effect); // 特殊效果
  const [selectedAnswer, setSelectedAnswer] = useState(null);
  
  // 根据关卡初始化Boss状态
  useEffect(() => {
    if (currentLevel <= 5) {
      const boss = bossConfig[currentLevel - 1];
      setBossHealth(boss.health);
      setBossAttack(boss.attack);
      setBossSpecialEffect(boss.effect);
    }
  }, [currentLevel, bossConfig]);
  
  // 题目状态
  const [currentQuestion, setCurrentQuestion] = useState(null);
  const [questionBank, setQuestionBank] = useState([]);
  const [currentQuestionIndex, setCurrentQuestionIndex] = useState(0);
  // 移除未使用的remainingQuestions状态
  
  // 加载状态
  const [loading, setLoading] = useState(true);
  const [loadingProgress, setLoadingProgress] = useState(0);
  const [loadingStatus, setLoadingStatus] = useState('正在准备生成题库...');
  const [loadingComplete, setLoadingComplete] = useState(false);
  const [earnedDice, setEarnedDice] = useState(0);
  
  // 离线模式状态
  const [isOfflineMode, setIsOfflineMode] = useState(false);
  
  // 弹窗状态
  const [resultModal, setResultModal] = useState({
    visible: false,
    isCorrect: false,
    explanation: '',
    question: '',
    selectedOption: '',
    correctOption: ''
  });
  const [diceModal, setDiceModal] = useState({
    visible: false,
    result: null,
    effect: ''
  });
  const [gameOverModal, setGameOverModal] = useState({
    visible: false,
    isWin: false,
    finalQuestion: null,
    selectedAnswer: null
  });
  const [effectModal, setEffectModal] = useState({
    visible: false,
    title: '',
    description: ''
  });
  
  // 添加全局变量，跟踪所有已使用的题目
  const [allUsedQuestions, setAllUsedQuestions] = useState([]);

  // 首先，添加一个新的Modal状态来显示击败Boss的通关页面
  const [bossDefeatedModal, setBossDefeatedModal] = useState({
    visible: false,
    level: 1,
    isSpecialReward: false
  });

  // 完全重构generateQuestions函数，添加批量请求和缓存机制
  const generateQuestions = React.useCallback(async (previousQuestions = []) => {
    // 如果已经有请求在进行中，则不再发起新请求
    if (requestInProgressRef.current) {
      console.log('已有题目请求正在进行中，跳过此次请求');
      return;
    }

    if (!gameParams?.cases || !Array.isArray(gameParams.cases) || gameParams.cases.length === 0) {
      setLoadingStatus('请选择案例类型');
      setLoading(false);
      return;
    }

    try {
      requestInProgressRef.current = true;
      setLoading(true);
      setLoadingProgress(0);
      setLoadingStatus('正在连接AI服务...');
      
      // 添加模拟进度更新
      const progressInterval = setInterval(() => {
        setLoadingProgress(prev => {
          // 如果进度已经很高，就不要再增加了
          if (prev >= 90) return prev;
          // 随机增加一点进度，但增长越来越慢
          const increment = Math.max(1, Math.floor(10 * Math.random() * (100 - prev) / 100));
          return Math.min(90, prev + increment);
        });
      }, 800);
      
      console.log('开始生成题目，案例类型:', gameParams.cases);
      
      // 从本地存储中获取缓存的题目
      const cachedQuestionsString = localStorage.getItem('cachedQuestions');
      let cachedQuestions = [];
      
      if (cachedQuestionsString) {
        try {
          cachedQuestions = JSON.parse(cachedQuestionsString);
          console.log(`从缓存中找到${cachedQuestions.length}道题目`);
          setLoadingProgress(15);
          setLoadingStatus(`从缓存中找到${cachedQuestions.length}道题目`);
        } catch (e) {
          console.error('解析缓存题目失败:', e);
          // 如果解析失败，清空缓存
          localStorage.removeItem('cachedQuestions');
          cachedQuestions = [];
          setLoadingProgress(15);
          setLoadingStatus('缓存解析失败，需要重新获取题目');
        }
      } else {
        setLoadingProgress(15);
        setLoadingStatus('未找到缓存题目，准备获取新题目');
      }
      
      // 强制始终请求API，不使用缓存
      if (false && cachedQuestions.length >= 10) {
        clearInterval(progressInterval); // 清除模拟进度
        
        console.log('使用缓存的题目，无需请求API');
        setLoadingProgress(70);
        setLoadingStatus('从缓存加载题库...');
        
        // 随机抽取5道题目
        const randomQuestions = getRandomQuestions(cachedQuestions, 5);
        
        // 更新已使用题目列表
        setAllUsedQuestions(prev => {
          const newUsedQuestions = [...prev];
          const questionsToPush = randomQuestions.map(q => ({
            question: q.question,
            options: q.options,
            answer: q.answer || (q.correctAnswer !== undefined ? String.fromCharCode(65 + q.correctAnswer) : 'A')
          }));
          
          newUsedQuestions.push(...questionsToPush);
          console.log('添加当前题库到已使用列表:', questionsToPush.length, '道题');
          console.log('已使用题目总数:', newUsedQuestions.length);
          
          return newUsedQuestions;
        });
        
        setLoadingProgress(90);
        setLoadingStatus('准备题目界面...');
        
        // 设置题库
        setQuestionBank(randomQuestions);
        setCurrentQuestion(randomQuestions[0]);
        setCurrentQuestionIndex(0);
        setIsOfflineMode(false);
        
        console.log('题库更新为缓存题库:', {
          count: randomQuestions.length,
          firstQuestion: randomQuestions[0].question,
          lastQuestion: randomQuestions[randomQuestions.length-1].question
        });
        
        setLoadingProgress(100);
        setLoadingStatus('题库加载完成！');
        
        // 设置加载完成状态，但不立即关闭加载界面
        setLoadingComplete(true);
        
        return;
      }
      
      // 如果缓存中题目不足，需要请求API
      setLoadingProgress(20);
      setLoadingStatus('准备批量生成题目...');
      
      // 批量请求6次，每次5道题
      const batchCount = 6;
      const batchPromises = [];
      
      for (let i = 0; i < batchCount; i++) {
        // 更新每个批次的开始状态
        setLoadingStatus(`正在生成第${i + 1}/${batchCount}批题目...`);
        
        batchPromises.push(
          fetch('http://localhost:5000/api/questions/generate', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify({
              gameType: gameParams.gameType || '民法',
              caseTypes: gameParams.cases,
              previousQuestions: previousQuestions,
              useTempBank: true
            })
          }).then(response => {
            if (!response.ok) {
              throw new Error(`API请求失败: ${response.status}`);
            }
            // 每个请求成功后更新进度
            const progressBase = 20;
            const progressPerBatch = 50 / batchCount;
            const newProgress = progressBase + Math.floor((i + 1) * progressPerBatch);
            setLoadingProgress(newProgress);
            setLoadingStatus(`完成第${i + 1}/${batchCount}批题目 (${newProgress}%)`);
            return response.json();
          })
        );
      }
      
      // 等待所有请求完成
      clearInterval(progressInterval); // 清除模拟进度，使用实际进度
      setLoadingStatus('等待所有题目生成完成...');
      const results = await Promise.allSettled(batchPromises);
      setLoadingProgress(75);
      setLoadingStatus('处理题库数据...');
      
      // 收集所有成功的题目
      let allQuestions = [];
      let successCount = 0;
      results.forEach((result, index) => {
        if (result.status === 'fulfilled') {
          const data = result.value;
          if (data && (Array.isArray(data.questions) || Array.isArray(data))) {
            const questions = Array.isArray(data.questions) ? data.questions : data;
            allQuestions = [...allQuestions, ...questions];
            successCount++;
            console.log(`批次${index + 1}成功获取${questions.length}道题目`);
          }
        } else {
          console.error(`批次${index + 1}请求失败:`, result.reason);
        }
      });
      
      setLoadingProgress(85);
      setLoadingStatus(`成功完成${successCount}/${batchCount}批次请求，正在整合题库...`);
      
      // 如果没有成功获取任何题目，抛出错误
      if (allQuestions.length === 0) {
        throw new Error('所有API请求均未返回有效题目');
      }
      
      console.log(`成功获取${allQuestions.length}道题目`);
      
      // 将所有题目存入缓存
      localStorage.setItem('cachedQuestions', JSON.stringify(allQuestions));
      
      setLoadingProgress(90);
      setLoadingStatus(`已缓存${allQuestions.length}道题目，正在准备游戏...`);
      
      // 使用所有获取的题目，不再随机抽取
      setLoadingProgress(95);
      setLoadingStatus('题库生成完成，准备游戏界面...');
      
      // 更新已使用题目列表
      setAllUsedQuestions(prev => {
        const newUsedQuestions = [...prev];
        const questionsToPush = allQuestions.map(q => ({
          question: q.question,
          options: q.options,
          answer: q.answer || (q.correctAnswer !== undefined ? String.fromCharCode(65 + q.correctAnswer) : 'A')
        }));
        
        newUsedQuestions.push(...questionsToPush);
        console.log('添加当前题库到已使用列表:', questionsToPush.length, '道题');
        console.log('已使用题目总数:', newUsedQuestions.length);
        
        return newUsedQuestions;
      });
      
      // 设置题库 - 使用所有题目
      setQuestionBank(allQuestions);
      setCurrentQuestion(allQuestions[0]);
      setCurrentQuestionIndex(0);
      setIsOfflineMode(false);
      
      console.log('题库更新为新题库:', {
        count: allQuestions.length,
        firstQuestion: allQuestions[0].question,
        lastQuestion: allQuestions[allQuestions.length-1].question
      });
      
      setLoadingProgress(100);
      setLoadingStatus('题库加载完成！');
      
      // 设置加载完成状态，但不立即关闭加载界面
      // 等待拼接游戏完成当前轮次后再关闭
      setLoadingComplete(true);
      
    } catch (error) {
      console.error('生成题目失败:', error);
      setIsOfflineMode(true);
      setLoadingProgress(50);
      setLoadingStatus(`生成题目失败: ${error.message}，尝试加载本地题库...`);
      
      // 生成本地题库
      const localQuestions = generateLocalQuestions(gameParams.cases);
      if (!localQuestions || localQuestions.length === 0) {
        setLoadingStatus('本地题库为空，请检查网络或联系管理员。');
        setLoadingProgress(100);
        // 设置加载完成状态，但不立即关闭加载界面
        setLoadingComplete(true);
        return;
      }
      
      setQuestionBank(localQuestions);
      setCurrentQuestion(localQuestions[0]);
      setCurrentQuestionIndex(0);
      setLoadingProgress(100);
      setLoadingStatus('本地题库加载完成！');
      
      // 设置加载完成状态，但不立即关闭加载界面
      setLoadingComplete(true);
    } finally {
      requestInProgressRef.current = false;
    }
  }, [gameParams]);

  // 从题目数组中随机选择指定数量的题目
  const getRandomQuestions = (questions, count) => {
    if (!questions || !Array.isArray(questions) || questions.length === 0) {
      console.error('无效的题目数组');
      return [];
    }
    
    // 如果题目数量不足，返回所有题目
    if (questions.length <= count) {
      console.log(`题目数量(${questions.length})不足${count}道，返回所有题目`);
      return [...questions];
    }
    
    // 随机选择题目
    const shuffled = [...questions].sort(() => 0.5 - Math.random());
    const selected = shuffled.slice(0, count);
    
    console.log(`从${questions.length}道题目中随机选择了${selected.length}道题目`);
    return selected;
  };

  // 初始化题库 - 使用isInitialLoadRef确保只加载一次
  useEffect(() => {
    const initQuestions = async () => {
      if (!gameParams?.cases || !isInitialLoadRef.current || isLoadingRef.current) {
        return;
      }
      
      try {
        isInitialLoadRef.current = false;
        isLoadingRef.current = true;
        setLoading(true);
        
        await generateQuestions([]);
      } finally {
        isLoadingRef.current = false;
      }
    };
    
    initQuestions();
  }, [generateQuestions, gameParams?.cases]);

  // 记录初始状态以便调试
  useEffect(() => {
    console.log('初始玩家状态:', {
      health: player.health,
      attack: player.attack,
      dice: player.dice,
      style: player.style
    });
  }, [player]);
  
  // 生成本地题库
  const generateLocalQuestions = (caseTypes) => {
    // 这里应该返回一些默认题目，或者提示"本地题库为空"
    // 示例：返回空数组，触发上方loading提示
    return [];
  };
  
  // 添加题目切换日志
  useEffect(() => {
    if (currentQuestion) {
      console.log('当前题目:', {
        index: currentQuestionIndex,
        total: questionBank.length,
        question: currentQuestion.question
      });
    }
  }, [currentQuestion, currentQuestionIndex, questionBank.length]);
  
  
  
  // 处理答案提交 (优化答案识别逻辑)
  const handleAnswer = () => {
    if (!selectedAnswer || !currentQuestion || !currentQuestion.options) {
      console.error('无效的答题状态:', { selectedAnswer, currentQuestion });
      return;
    }

    // 确保selectedAnswer是字符串格式
    const selectedOption = typeof selectedAnswer === 'string' ? selectedAnswer : '';
    const selectedIndex = selectedOption.charCodeAt(0) - 65; // A=0, B=1, etc.
    
    // 验证选项索引是否有效
    if (selectedIndex < 0 || selectedIndex >= currentQuestion.options.length) {
      console.error('无效的选项索引:', selectedIndex);
      return;
    }

    // 获取正确答案索引
    let correctIndex = currentQuestion.correctAnswer;
    
    // 如果correctIndex无效，尝试从answer文本解析
    if (correctIndex === undefined || correctIndex >= currentQuestion.options.length) {
      console.warn('无效的正确答案索引:', correctIndex, '尝试从answer解析...');
      if (currentQuestion.answer) {
        const answerText = currentQuestion.answer.trim().toUpperCase();
        correctIndex = answerText.charCodeAt(0) - 65; // A=0, B=1, etc.
        if (correctIndex >= 0 && correctIndex < currentQuestion.options.length) {
          console.log('从answer解析出正确答案索引:', correctIndex);
          // 更新题目对象中的correctAnswer
          currentQuestion.correctAnswer = correctIndex;
        } else {
          console.error('无法从answer解析正确答案:', answerText);
          correctIndex = 0; // 默认第一个选项
        }
      } else {
        console.error('题目缺少correctAnswer和answer字段');
        correctIndex = 0; // 默认第一个选项
      }
    }
    
    // 确保correctIndex在有效范围内
    correctIndex = Math.max(0, Math.min(correctIndex, currentQuestion.options.length - 1));

    const isCorrect = selectedIndex === correctIndex;
    
    // 记录答题日志
    console.log('题目答案验证:', {
      question: currentQuestion.question,
      userAnswer: selectedOption,
      correctAnswer: String.fromCharCode(65 + correctIndex),
      isCorrect
    });
    
    if (isCorrect) {
      // 答对时的逻辑
      const newBossHealth = Math.max(0, bossHealth - player.attack);
      setBossHealth(newBossHealth);
      
      // 检查是否击败当前关卡Boss
      if (newBossHealth <= 0) {
        // 玩家击败Boss后获得一个律迹骰
        dispatchPlayer({ type: 'ADD_DICE', payload: 1 });
        
        // 检查是否还有下一关
        if (currentLevel < bossConfig.length) {
          // 检查下一关是否为特殊奖励关(第3关)
          const isNextLevelSpecial = currentLevel + 1 === 3;
          
          // 显示Boss击败弹窗
          setBossDefeatedModal({
            visible: true,
            level: currentLevel,
            isSpecialReward: isNextLevelSpecial
          });
          
          // 此处不再自动进入下一关，而是通过弹窗中的按钮进行
        } else {
          // 通关所有关卡
          setGameOverModal({
            visible: true,
            isWin: true,
            finalQuestion: currentQuestion,
            selectedAnswer: selectedAnswer
          });
        }
      }
    } else {
      // 答错时的逻辑
      dispatchPlayer({ type: 'LOSE_HEALTH' });
      
      // 检查玩家是否失败
      if (player.health <= 1) {
        setGameOverModal({
          visible: true,
          isWin: false,
          finalQuestion: currentQuestion,
          selectedAnswer: selectedAnswer
        });
      }
    }
    
    // 显示结果弹窗
    setResultModal({
      visible: true,
      isCorrect,
      question: currentQuestion.question,
      explanation: currentQuestion.explanation,
      selectedAnswer: selectedAnswer,
      selectedOption: `${selectedAnswer}. ${currentQuestion.options[selectedIndex]}`,
      correctOption: `${String.fromCharCode(65 + currentQuestion.correctAnswer)}. ${currentQuestion.options[currentQuestion.correctAnswer]}`
    });
  };
  
  // 重新生成题目 - 使用防抖避免重复请求
  const regenerateQuestions = React.useCallback(debounce(async () => {
    if (requestInProgressRef.current) {
      console.log('已有题目请求正在进行中，跳过重新生成');
      return;
    }
    
    try {
      setLoading(true);
      setLoadingProgress(0);
      setLoadingStatus('正在生成新题库...');
      
      await generateQuestions([]);
      
      console.log('已完成新题库生成，进入第一题');
    } catch (error) {
      console.error('重新生成题目失败:', error);
      setLoadingStatus(`重新生成题目失败: ${error.message}`);
      setLoading(false);
    }
  }, 500), [generateQuestions]);
  
  // 使用骰子
  const useDice = () => {
    if (player.dice <= 0) {
      alert('没有可用的骰子');
      return;
    }
    
    // 随机生成1-6的数字
    const diceResult = Math.floor(Math.random() * 6) + 1;
    
    // 根据骰子结果应用效果
    let effect = '';
    switch (diceResult) {
      case 1:
        dispatchPlayer({ type: 'ADD_HEALTH', payload: 3 });
        effect = '增加3点法盾值';
        break;
      case 2:
        dispatchPlayer({ type: 'ADD_ATTACK', payload: 3 });
        effect = '增加3点律刃值';
        break;
      case 3:
        dispatchPlayer({ type: 'ADD_HEALTH', payload: 2 });
        dispatchPlayer({ type: 'ADD_ATTACK', payload: 2 });
        effect = '增加2点法盾值和2点律刃值';
        break;
      case 4:
        dispatchPlayer({ type: 'ADD_DICE', payload: 1 });
        effect = '增加1个律迹骰';
        break;
      case 5:
        dispatchPlayer({ type: 'MULTIPLY_ATTACK', payload: 2 });
        effect = '律刃值翻倍';
        break;
      case 6:
        dispatchPlayer({ type: 'MULTIPLY_HEALTH', payload: 2 });
        effect = '法盾值翻倍';
        break;
      default:
        effect = '没有效果';
    }
    
    // 扣除使用的骰子
    dispatchPlayer({ type: 'USE_DICE' });
    
    // 显示骰子结果弹窗
    setDiceModal({
      visible: true,
      result: diceResult,
      effect
    });
  };
  
  // 处理继续游戏 - 优化切换逻辑，防止重复请求
  const handleContinue = React.useCallback(() => {
    setResultModal(prev => ({ ...prev, visible: false }));
    setSelectedAnswer(null);

    // 日志追踪
    console.log('handleContinue', {
      currentQuestionIndex,
      questionBankLength: questionBank.length,
      playerHealth: player.health,
      bossHealth,
      bossAttack
    });

    // 如果游戏已经结束，不继续下一题
    if (player.health <= 0 || bossHealth <= 0) {
      console.log('游戏已结束，不再切题');
      return;
    }

    // 检查题库是否为空
    if (questionBank.length === 0) {
      console.warn('题库为空，无法切换题目');
      setLoadingStatus('题库为空，请重新生成题库');
      setLoading(true);
      return;
    }

    // 计算下一题索引
    let nextIndex = currentQuestionIndex + 1;
    if (nextIndex >= questionBank.length) {
      // 已到题库末尾，从缓存中获取新题目
      const cachedQuestionsString = localStorage.getItem('cachedQuestions');
      
      if (cachedQuestionsString) {
        try {
          const cachedQuestions = JSON.parse(cachedQuestionsString);
          if (cachedQuestions.length > 0) {
            // 从缓存中随机抽取5道题目
            const randomQuestions = getRandomQuestions(cachedQuestions, 5);
            
            // 更新已使用题目列表
            setAllUsedQuestions(prev => {
              const newUsedQuestions = [...prev];
              const questionsToPush = randomQuestions.map(q => ({
                question: q.question,
                options: q.options,
                answer: q.answer || (q.correctAnswer !== undefined ? String.fromCharCode(65 + q.correctAnswer) : 'A')
              }));
              
              newUsedQuestions.push(...questionsToPush);
              console.log('添加当前题库到已使用列表:', questionsToPush.length, '道题');
              console.log('已使用题目总数:', newUsedQuestions.length);
              
              return newUsedQuestions;
            });
            
            // 设置题库
            setQuestionBank(randomQuestions);
            setCurrentQuestion(randomQuestions[0]);
            setCurrentQuestionIndex(0);
            
            console.log('从缓存更新题库:', {
              count: randomQuestions.length,
              firstQuestion: randomQuestions[0].question,
              lastQuestion: randomQuestions[randomQuestions.length-1].question
            });
            
            return;
          }
        } catch (e) {
          console.error('解析缓存题目失败:', e);
        }
      }
      
      // 如果缓存中没有题目或解析失败，则重新生成题目
      setLoading(true);
      setLoadingStatus('正在生成新题库...');
      regenerateQuestions();
      return;
    }

    // 切换到下一题
    setCurrentQuestionIndex(nextIndex);
    setCurrentQuestion(questionBank[nextIndex]);
    console.log('切换到下一题', { nextIndex, question: questionBank[nextIndex]?.question });
  }, [currentQuestionIndex, questionBank, player.health, bossHealth, bossAttack, regenerateQuestions]);

  // 添加处理进入下一关的函数
  const handleNextLevel = () => {
    // 关闭Boss击败弹窗
    setBossDefeatedModal({ ...bossDefeatedModal, visible: false });
    
    // 检查是否为进入奖励关(第3关)
    if (currentLevel + 1 === 3) {
      // 在进入第3关(奖励关)时给予玩家额外奖励
      dispatchPlayer({ type: 'ADD_HEALTH', payload: 10 });
      dispatchPlayer({ type: 'ADD_ATTACK', payload: 5 });
    }
    
    // 进入下一关
    setCurrentLevel(currentLevel + 1);
    // 重置当前题目索引
    setCurrentQuestionIndex(0);
  };

  // 确保题目加载后正确设置当前题目
  useEffect(() => {
    if (questionBank.length > 0 && currentQuestionIndex < questionBank.length) {
      setCurrentQuestion(questionBank[currentQuestionIndex]);
    }
  }, [questionBank, currentQuestionIndex]);

  // 组件卸载时清理所有题库相关存储
  useEffect(() => {
    return () => {
      sessionStorage.removeItem('answeredQuestions');
      setAllUsedQuestions([]);
    };
  }, []);
  
  // 处理拼接游戏获得骰子
  const handleEarnDice = (diceCount) => {
    setEarnedDice(prev => prev + diceCount);
    dispatchPlayer({ type: 'ADD_DICE', payload: diceCount });
  };

  // 处理拼接游戏完成
  const handlePuzzleComplete = () => {
    // 当拼接游戏完成且加载完成后，才关闭加载界面
    if (loadingComplete) {
      setLoading(false);
    }
  };

  // 改进加载界面显示
  const renderLoading = () => {
    return (
      <div className="loading-container">
        <div className="loading-content">
          <h2>正在准备题库...</h2>
          <Progress 
            percent={loadingProgress} 
            status={loadingComplete ? "success" : "active"}
            strokeColor={{
              '0%': '#108ee9',
              '100%': '#87d068',
            }}
            strokeWidth={8}
          />
          <p style={{ 
            marginTop: '15px', 
            fontSize: '16px',
            color: loadingComplete ? '#52c41a' : '#1890ff'
          }}>
            {loadingComplete ? '题库准备完成，请完成当前拼接游戏' : loadingStatus}
          </p>
          {!loadingComplete && (
            <div style={{ marginTop: '10px', fontSize: '14px', color: '#888' }}>
              {loadingProgress < 30 ? '正在连接服务器...' : 
               loadingProgress < 60 ? '正在生成题目...' : 
               loadingProgress < 90 ? '正在处理数据...' : '即将完成...'}
            </div>
          )}
          {isOfflineMode && (
            <Alert
              message="离线模式"
              description="无法连接到后端服务器，已切换到本地题库模式。本地题库可能不会完全匹配您选择的案例类型。"
              type="warning"
              showIcon
              style={{ marginTop: '20px' }}
            />
          )}
          
          {/* 法律概念拼接游戏 */}
          <div style={{ marginTop: '30px' }}>
            <Divider>在等待时玩个小游戏吧</Divider>
            <LegalConceptPuzzle 
              conceptBank={legalConcepts}
              onEarnDice={handleEarnDice}
              onComplete={handlePuzzleComplete}
              isLoadingComplete={loadingComplete}
            />
          </div>
        </div>
      </div>
    );
  };
  
  return (
    <Layout style={{ minHeight: '100vh', background: '#f0f2f5' }}>
      {loading ? (
        renderLoading()
      ) : (
        <>
          <Header style={{ background: '#1890ff', padding: '0 20px' }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <Title level={3} style={{ color: 'white', margin: '0' }}>法链云迹 - 闯关游戏</Title>
            </div>
          </Header>
          
          <Content style={{ padding: '20px 24px', textAlign: 'center' }}>
            {/* 玩家和Boss状态显示 - 更新名称和图标 */}
            <div className="status-container">
              <div className="player-status">
                <Title level={4}>玩家状态</Title>
                <div className="status-info">
                  <div className="status-item">
                    <span className="status-label">法盾值 <span role="img" aria-label="shield">🛡️</span></span>
                    <Progress 
                      percent={player.health * 25} 
                      strokeColor={{
                        '0%': '#ff4d4f',
                        '100%': '#ff7875',
                      }}
                      showInfo={false}
                    />
                    <span className="status-value">{player.health}</span>
                  </div>
                  <div className="status-item">
                    <span className="status-label">律刃值 <span role="img" aria-label="sword">⚔️</span></span>
                    <Progress 
                      percent={player.attack * 33.33} 
                      strokeColor={{
                        '0%': '#ffa940',
                        '100%': '#ffc069',
                      }}
                      showInfo={false}
                    />
                    <span className="status-value">{player.attack}</span>
                  </div>
                  <div className="status-item">
                    <span className="status-label">律迹骰 <span role="img" aria-label="dice">🎲</span></span>
                    <div className="dice-count">
                      {[...Array(player.dice)].map((_, i) => (
                        <span key={i} role="img" aria-label="dice">🎲</span>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
              
              <div className="boss-status">
                <Title level={4}>Boss状态</Title>
                <div className="status-info">
                  <div className="status-item">
                    <span className="status-label">法熵值 <span role="img" aria-label="entropy">☯️</span></span>
                    <Progress 
                      percent={bossHealth * 10} 
                      strokeColor={{
                        '0%': '#722ed1',
                        '100%': '#8b0000',
                      }}
                      showInfo={false}
                    />
                    <span className="status-value">{bossHealth}</span>
                  </div>
                  <div className="status-item">
                    <span className="status-label">侵权烈度 <span role="img" aria-label="lightning">⚡</span></span>
                    <div className="attack-points">
                      {Array.from({ length: bossAttack }).map((_, i) => (
                        <span key={i}>✦</span>
                      ))}
                    </div>
                  </div>
                  <div className="status-item">
                    <span className="status-label">特殊效果 <span role="img" aria-label="sparkles">✨</span></span>
                    <div 
                      className="special-effect clickable" 
                      onClick={() => setEffectModal({
                        visible: true,
                        title: bossSpecialEffect.name,
                        description: bossSpecialEffect.description
                      })}
                    >
                      {bossSpecialEffect.name}
                    </div>
                  </div>
                </div>
              </div>
            </div>
            
            {currentQuestion ? (
              <div className="question-container">
                <Title level={3} style={{ marginBottom: 30, textAlign: 'left' }}>
                  <span role="img" aria-label="scroll" style={{ marginRight: 8 }}>📜</span>
                  {currentQuestion.question}
                </Title>
                
                <div className="options-grid">
                  {currentQuestion.options.map((option, index) => (
                    option && (
                      <Button 
                        key={index}
                        type={selectedAnswer === String.fromCharCode(65 + index) ? 'primary' : 'default'}
                        size="large"
                        className={`option-button ${selectedAnswer === String.fromCharCode(65 + index) ? 'selected' : ''}`}
                        onClick={() => setSelectedAnswer(String.fromCharCode(65 + index))}
                      >
                        <span className="option-value">{option}</span>
                      </Button>
                    )
                  ))}
                </div>
              </div>
            ) : (
              <div className="loading-question">
                <Spin size="large" />
                <p>正在准备下一道题目...</p>
              </div>
            )}
          </Content>
          
          <Footer style={{ textAlign: 'center', padding: '20px 24px' }}>
            <Button 
              type="primary" 
              size="large"
              className="action-button confirm-button"
              onClick={handleAnswer}
              disabled={!selectedAnswer}
            >
              <span role="img" aria-label="confirm" style={{ marginRight: 8 }}>⚔️</span>
              确定
            </Button>
            <Button 
              type="default" 
              size="large"
              className="action-button dice-button"
              onClick={useDice}
              disabled={player.dice <= 0}
            >
              <span role="img" aria-label="dice" style={{ marginRight: 8 }}>🎲</span>
              使用律迹骰
            </Button>
          </Footer>
          
          {/* 特殊效果描述弹窗 */}
          <Modal
            title={`特殊效果: ${effectModal.title}`}
            open={effectModal.visible}
            onOk={() => setEffectModal({...effectModal, visible: false})}
            onCancel={() => setEffectModal({...effectModal, visible: false})}
            okText="确定"
            cancelText="关闭"
          >
            <div>
              <Paragraph>
                <strong>效果描述:</strong>
              </Paragraph>
              <Paragraph style={{ textIndent: '2em' }}>
                {effectModal.description}
              </Paragraph>
            </div>
          </Modal>
          
          {/* 结果弹窗 */}
          <Modal
            title={resultModal.isCorrect ? "回答正确!" : "回答错误!"}
            open={resultModal.visible}
            onOk={handleContinue}
            onCancel={handleContinue}
            okText="继续"
            cancelText="关闭"
          >
            <ResultModalContent
              isCorrect={resultModal.isCorrect}
              question={resultModal.question}
              explanation={resultModal.explanation}
              selectedOption={resultModal.selectedOption}
              correctOption={resultModal.correctOption}
            />
          </Modal>
          
          {/* 骰子结果弹窗 */}
          <Modal
            title="律迹骰结果"
            open={diceModal.visible}
            onOk={() => setDiceModal({ ...diceModal, visible: false })}
            onCancel={() => setDiceModal({ ...diceModal, visible: false })}
            okText="确定"
            cancelText="关闭"
          >
            <DiceModalContent
              result={diceModal.result}
              effect={diceModal.effect}
            />
          </Modal>
          
          {/* 添加Boss击败弹窗 */}
          <Modal
            title={`第${bossDefeatedModal.level}关通关!`}
            open={bossDefeatedModal.visible}
            onOk={handleNextLevel}
            okText="进入下一关"
            closable={false}
            maskClosable={false}
            keyboard={false}
          >
            <div className="boss-defeated-content" style={{ textAlign: 'center' }}>
              <motion.div 
                initial={{ scale: 0 }}
                animate={{ scale: 1 }}
                transition={{ type: "spring", stiffness: 260, damping: 20 }}
              >
                <div style={{ fontSize: '60px', margin: '20px 0' }}>🏆</div>
              </motion.div>
              
              <AnimatedText
                text={`恭喜击败第${bossDefeatedModal.level}关Boss!`}
                type="highlight"
                fontSize="24px"
                fontWeight="bold"
                color="var(--primary-color)"
                style={{ marginBottom: '20px' }}
              />
              
              <div style={{ 
                backgroundColor: 'rgba(166, 124, 0, 0.1)', 
                padding: '15px', 
                borderRadius: '8px',
                marginBottom: '20px' 
              }}>
                <AnimatedText
                  text="你获得了一个律迹骰! 🎲"
                  type="slideDown"
                  fontSize="18px"
                  fontWeight="bold"
                  color="var(--secondary-color)"
                />
                
                <motion.div
                  initial={{ y: 20, opacity: 0 }}
                  animate={{ y: 0, opacity: 1 }}
                  transition={{ delay: 0.5 }}
                  style={{ marginTop: '10px' }}
                >
                  <AnimatedDice value={Math.floor(Math.random() * 6) + 1} size={70} />
                </motion.div>
              </div>
              
              {bossDefeatedModal.isSpecialReward && (
                <div style={{
                  backgroundColor: 'rgba(24, 144, 255, 0.1)',
                  padding: '15px',
                  borderRadius: '8px',
                  marginBottom: '20px'
                }}>
                  <AnimatedText
                    text="下一关为奖励关!"
                    type="fade"
                    fontSize="18px"
                    fontWeight="bold"
                    color="#1890ff"
                    style={{ marginBottom: '10px' }}
                  />
                  
                  <AnimatedText
                    text="你将获得额外10点法盾值和5点律刃值!"
                    type="highlight"
                    delay={0.3}
                    color="#1890ff"
                  />
                </div>
              )}
              
              <Button 
                type="primary"
                size="large"
                onClick={handleNextLevel}
                style={{ marginTop: '10px' }}
              >
                进入下一关
              </Button>
            </div>
          </Modal>
          
          {/* 游戏结束弹窗 */}
          <Modal
            title={gameOverModal.isWin ? "恭喜通关!" : "游戏结束"}
            open={gameOverModal.visible}
            onOk={() => navigate('/')}
            onCancel={() => navigate('/')}
            okText="返回首页"
            cancelText="返回首页"
            closable={false}
            maskClosable={false}
            keyboard={false}
          >
            <div className="game-over-content">
              {gameOverModal.isWin ? (
                <>
                  <motion.div 
                    initial={{ scale: 0 }}
                    animate={{ scale: 1 }}
                    transition={{ type: "spring", stiffness: 260, damping: 20 }}
                    style={{ textAlign: 'center' }}
                  >
                    <div style={{ fontSize: '80px', margin: '20px 0' }}>🏅</div>
                  </motion.div>
                  
                  <AnimatedText
                    text="恭喜你通关游戏！"
                    type="highlight"
                    fontSize="24px"
                    fontWeight="bold"
                    color="var(--primary-color)"
                    textAlign="center"
                    style={{ marginBottom: '20px' }}
                  />
                  
                  <div style={{ 
                    textAlign: 'center',
                    backgroundColor: 'rgba(166, 124, 0, 0.1)', 
                    padding: '15px', 
                    borderRadius: '8px',
                    marginBottom: '20px' 
                  }}>
                    <AnimatedText
                      text="你获得了一个律迹骰! 🎲"
                      type="slideDown"
                      fontSize="18px"
                      fontWeight="bold"
                      color="var(--secondary-color)"
                    />
                    
                    <motion.div
                      initial={{ y: 20, opacity: 0 }}
                      animate={{ y: 0, opacity: 1 }}
                      transition={{ delay: 0.5 }}
                      style={{ marginTop: '10px' }}
                    >
                      <AnimatedDice value={Math.floor(Math.random() * 6) + 1} size={70} />
                    </motion.div>
                  </div>
                </>
              ) : (
                <>
                  <p>很遗憾，你的法盾值已耗尽。</p>
                  <Divider />
                  <div className="final-question-review">
                    <Title level={4}>本题解析</Title>
                    <Paragraph>
                      <strong>题目：</strong> {gameOverModal.finalQuestion?.question}
                    </Paragraph>
                    <Paragraph>
                      <strong>你的选择：</strong>
                      <Tag color="error">
                        {gameOverModal.selectedAnswer}. {gameOverModal.finalQuestion?.options[gameOverModal.selectedAnswer.charCodeAt(0) - 65]}
                      </Tag>
                    </Paragraph>
                    <Paragraph>
                      <strong>正确答案：</strong>
                      <Tag color="success">
                        {String.fromCharCode(65 + gameOverModal.finalQuestion?.correctAnswer)}. {gameOverModal.finalQuestion?.options[gameOverModal.finalQuestion?.correctAnswer]}
                      </Tag>
                    </Paragraph>
                    <Divider />
                    <Paragraph>
                      <strong>解析：</strong>
                    </Paragraph>
                    <Paragraph style={{ textIndent: '2em' }}>
                      {gameOverModal.finalQuestion?.explanation}
                    </Paragraph>
                  </div>
                </>
              )}
            </div>
          </Modal>
        </>
      )}
    </Layout>
  );
};

// 添加动画组件

// 答案选项动画组件
const AnimatedOption = ({ children, index, isSelected, onClick }) => (
  <motion.div
    initial={{ opacity: 0, y: 20 }}
    animate={{ opacity: 1, y: 0 }}
    transition={{ duration: 0.5, delay: 0.2 + index * 0.1 }}
    whileHover={{ scale: 1.02, boxShadow: '0 5px 15px rgba(0,0,0,0.1)' }}
    whileTap={{ scale: 0.98 }}
    onClick={onClick}
    style={{
      padding: '15px',
      border: `2px solid ${isSelected ? 'var(--secondary-color)' : '#d9d9d9'}`,
      borderRadius: '8px',
      margin: '10px 0',
      cursor: 'pointer',
      background: isSelected ? 'rgba(166, 124, 0, 0.1)' : 'white',
      position: 'relative',
      transition: 'background 0.3s'
    }}
  >
    {isSelected && (
      <motion.div
        initial={{ opacity: 0 }}
        animate={{ opacity: 1 }}
        style={{
          position: 'absolute',
          top: '-10px',
          right: '-10px',
          width: '24px',
          height: '24px',
          borderRadius: '50%',
          background: 'var(--secondary-color)',
          color: 'white',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          fontWeight: 'bold'
        }}
      >
        ✓
      </motion.div>
    )}
    {children}
  </motion.div>
);

// Boss信息动画组件
const AnimatedBossInfo = ({ level, health, attack, effect }) => (
  <motion.div
    initial={{ opacity: 0, scale: 0.9 }}
    animate={{ opacity: 1, scale: 1 }}
    transition={{ duration: 0.5 }}
  >
    <LegalCard style="legal" title={
      <AnimatedText
        text={`第${level}关：${effect.name}`}
        type="fade"
        fontSize="18px"
        fontWeight="bold"
        color="var(--primary-color)"
      />
    }>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-around', flexWrap: 'wrap' }}>
        <div>
          <AnimatedText
            text="法熵值"
            type="fade"
            delay={0.2}
            style={{ display: 'block', marginBottom: '5px' }}
          />
          <motion.div
            initial={{ width: 0 }}
            animate={{ width: '100%' }}
            transition={{ duration: 0.8, delay: 0.3 }}
          >
            <Progress 
              percent={(health / (level * 10)) * 100} 
              format={() => health} 
              strokeColor={{ '0%': '#1a2b48', '100%': '#a67c00' }}
            />
          </motion.div>
        </div>
        <Tag color="red" style={{ margin: '10px', fontSize: '16px' }}>
          侵权烈度: {attack}
        </Tag>
        <motion.div
          initial={{ opacity: 0 }}
          animate={{ opacity: 1 }}
          transition={{ delay: 0.4 }}
          style={{ margin: '10px', fontSize: '14px', color: 'var(--accent-color)' }}
        >
          {effect.description}
        </motion.div>
      </div>
    </LegalCard>
  </motion.div>
);

// 玩家状态动画组件
const AnimatedPlayerStatus = ({ health, attack, dice, style }) => (
  <motion.div
    initial={{ opacity: 0, y: 20 }}
    animate={{ opacity: 1, y: 0 }}
    transition={{ duration: 0.5, delay: 0.3 }}
  >
    <LegalCard style="parchment" title={
      <AnimatedText
        text={`玩家状态 (${style === 'conservative' ? '保守型' : style === 'balanced' ? '稳健型' : '激进型'})`}
        type="fade"
        fontSize="18px"
        fontWeight="bold"
      />
    }>
      <div style={{ display: 'flex', flexWrap: 'wrap', justifyContent: 'space-around' }}>
        <motion.div 
          whileHover={{ scale: 1.05 }}
          style={{ margin: '10px', textAlign: 'center' }}
        >
          <AnimatedText
            text="法盾值"
            type="fade"
            delay={0.3}
            style={{ display: 'block' }}
          />
          <motion.div
            initial={{ scale: 0 }}
            animate={{ scale: 1 }}
            transition={{ type: 'spring', stiffness: 300, damping: 15, delay: 0.4 }}
            style={{ 
              fontSize: '28px', 
              fontWeight: 'bold', 
              color: 'var(--primary-color)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}
          >
            <span style={{ marginRight: '5px' }}>🛡️</span> {health}
          </motion.div>
        </motion.div>
        
        <motion.div 
          whileHover={{ scale: 1.05 }}
          style={{ margin: '10px', textAlign: 'center' }}
        >
          <AnimatedText
            text="律刃值"
            type="fade"
            delay={0.5}
            style={{ display: 'block' }}
          />
          <motion.div
            initial={{ scale: 0 }}
            animate={{ scale: 1 }}
            transition={{ type: 'spring', stiffness: 300, damping: 15, delay: 0.6 }}
            style={{ 
              fontSize: '28px', 
              fontWeight: 'bold',
              color: 'var(--accent-color)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}
          >
            <span style={{ marginRight: '5px' }}>⚔️</span> {attack}
          </motion.div>
        </motion.div>
        
        <motion.div 
          whileHover={{ scale: 1.05 }}
          style={{ margin: '10px', textAlign: 'center' }}
        >
          <AnimatedText
            text="律迹骰"
            type="fade"
            delay={0.7}
            style={{ display: 'block' }}
          />
          <motion.div
            initial={{ scale: 0 }}
            animate={{ scale: 1 }}
            transition={{ type: 'spring', stiffness: 300, damping: 15, delay: 0.8 }}
            style={{ 
              fontSize: '28px', 
              fontWeight: 'bold',
              color: 'var(--secondary-color)',
              display: 'flex',
              alignItems: 'center',
              justifyContent: 'center'
            }}
          >
            <span style={{ marginRight: '5px' }}>🎲</span> {dice}
          </motion.div>
        </motion.div>
      </div>
    </LegalCard>
  </motion.div>
);

// 结果弹窗内容组件
const ResultModalContent = ({ isCorrect, question, explanation, selectedOption, correctOption }) => (
  <div>
    <motion.div
      initial={{ scale: 0 }}
      animate={{ scale: 1 }}
      transition={{ type: 'spring', stiffness: 200, damping: 20 }}
      style={{ 
        textAlign: 'center', 
        marginBottom: '20px',
        fontSize: '36px'
      }}
    >
      {isCorrect ? '✅' : '❌'}
    </motion.div>
    
    <AnimatedText
      text={isCorrect ? '回答正确！' : '回答错误！'}
      type="highlight"
      fontSize="24px"
      fontWeight="bold"
      color={isCorrect ? 'var(--adventure-color)' : 'var(--accent-color)'}
      textAlign="center"
      style={{ marginBottom: '20px' }}
    />
    
    <LegalCard style="scroll">
      <AnimatedText
        text="题目解析："
        type="fade"
        delay={0.2}
        fontSize="18px"
        fontWeight="bold"
        style={{ marginBottom: '10px', display: 'block' }}
      />
      
      <AnimatedText
        text={explanation || "暂无解析"}
        type="fade"
        delay={0.4}
        style={{ display: 'block', textAlign: 'left' }}
      />
      
      {!isCorrect && (
        <div style={{ marginTop: '15px', padding: '10px', background: 'rgba(166, 124, 0, 0.1)', borderRadius: '4px' }}>
          <AnimatedText
            text={`正确答案：${correctOption}`}
            type="highlight"
            delay={0.6}
            fontWeight="bold"
          />
        </div>
      )}
    </LegalCard>
  </div>
);

// 骰子弹窗内容组件
const DiceModalContent = ({ result, effect }) => (
  <div style={{ textAlign: 'center' }}>
    <AnimatedText
      text="律迹骰效果"
      type="legal"
      fontSize="24px"
      fontWeight="bold"
      color="var(--primary-color)"
      textAlign="center"
      style={{ marginBottom: '20px' }}
    />
    
    <motion.div
      initial={{ y: -20, opacity: 0 }}
      animate={{ y: 0, opacity: 1 }}
      transition={{ duration: 0.5, delay: 0.2 }}
      style={{ marginBottom: '20px' }}
    >
      <AnimatedDice value={result} size={100} />
    </motion.div>
    
    <AnimatedText
      text={effect}
      type="highlight"
      delay={0.4}
      fontSize="18px"
      fontWeight="bold"
      color="var(--secondary-color)"
      textAlign="center"
    />
  </div>
);

export default GamePage;
